package common

//在golang中，main和init都会自动加载，一个程序中只能有一个init

import (
	"fmt"
	"github.com/micro/go-micro/v2/util/log"
	"github.com/streadway/amqp"
)

const (
	Exchange      = "test-exchange-homin"
	BindingQueue1 = "test_binding_key1"
	BindingQueue2 = "test_binding_key2"
	Topic1        = "test_topic1"
	Topic2        = "test_topic2"
)

var (
	conn *amqp.Connection
	ch   *amqp.Channel
)

/*
	消费者包含了：
	1、与rabbitmq的连接conn
	2、连接的通道channel
	3、消费者的自定义标签
	4、结束done_channel
*/
type Consumer struct {
	conn    *amqp.Connection
	Channel *amqp.Channel
	Tag     string
	Done    chan error
}

func InitMq() {
	//获取连接
	conn, err = amqp.Dial("amqp://guest:guest@localhost:5672")

	if err != nil {
		fmt.Errorf("Dial fail: %s", err)
	}
	//获取通道
	ch, err = conn.Channel()
	if err != nil {
		fmt.Errorf("get chan fail : %s", err)
	}
	//defer ch.Close()

	if err := ch.ExchangeDeclare( //绑定交换机
		Exchange,
		"direct",
		true,  // durable
		false, // delete when complete
		false, // internal
		false, // noWait
		nil,   // arguments
	); err != nil {
		log.Infof("ExchangeDeclare fail msg:%v", err)
	}

	return
}

func NewAmqpChannel() *Consumer {
	return &Consumer{
		conn,
		ch,
		"micro_rabbitmq",
		make(chan error),
	}
}

func Handle(msgs <-chan amqp.Delivery, done chan error) map[uint64][]byte {
	msgMap := make(map[uint64][]byte)
	//遍历消息
	for v := range msgs {
		log.Infof("Consumer got %d byte msg: [%v]%v", len(v.Body), v.DeliveryTag, string(v.Body))
		v.Ack(false)
		msgMap[v.DeliveryTag] = v.Body
	}
	return msgMap
}
